// pages/myeditor/myeditor.js
const config = require('../../utils/config');

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  editor:null,

  //初始化富文本编辑器
  initEditor() {
    let query = wx.createSelectorQuery();
    return new Promise((rv,rj)=>{
      query.select("#editor").context(res=>{
        this.editor = res.context;
        rv(this.editor)
      }).exec()
    })
    
  },

  timer:null,

  titleDetail:null,

  //缓存标题
  cacheTitle(e) {
    this.titleDetail = e.detail;
    if(this.timer) {
      return 
    }
    this.timer = setTimeout(()=>{
      console.log(this.titleDetail.value);
      wx.setStorageSync('title', this.titleDetail.value)
      this.timer = null;
    },500)
  },

  //缓存内容
  cacheContent() {
    if(this.timer) {
      return 
    }
    this.timer = setTimeout(()=>{
      this.editor.getContents({
        success:res=>{
          wx.setStorageSync('content', res.html)
        }
      })
    },500)
  },

  //表单内容提交
  postData(e) {
    console.log(e.detail.value.title)
    this.editor.getContents({
      success: res => {
        console.log(res.html)
        wx.request({
          url: `${config.apiUrl}/content`,
          method: "POST",
          data: {
            title:e.detail.value.title,
            content: res.html
          },
          success: res => {
            console.log(res)
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.initEditor().then(()=>{
      let content = wx.getStorageSync('content');
      content && this.editor.setContents({
        html:content
      })
    });

    let title = wx.getStorageSync('title')
    this.setData({
      title
    })
  },

  //插入图片
  async insertImage() {
    try {
      let ret = await new Promise((rv,rj) => {
        wx.chooseMedia({
          count:1,
          mediaType:["image"],
          sourceType:["album","camera"],
          sizeType:["original","compressed"],
          success: res => {
            rv(res);
          },
          fail: err => {
            rj(err);
          }
        })
      })
      
      let img_ret = await new Promise((rv,rj) => {
        //上传图片
        wx.uploadFile({
          filePath: ret.tempFiles[0].tempFilePath,
          name: 'image',
          url: `${config.apiUrl}/api/image`,
          success: res => {
            rv(res);
          },
          fail: err => {
            rj(err);
          }
        })
      })
  
      this.editor.insertImage({
        src: `${config.apiUrl}/public/image/${img_ret.data}`
      })
    } catch (error) {
      console.error(error)
    }
  },

  //撤销
  undo() {
    this.editor.undo();
  },

  //恢复
  redo() {
    this.editor.redo();
  },

  //清除所选区域的样式
  clearFormat() {
    this.editor.removeFormat({
      fail:res=>{
        console.error(res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(!this.editor) {
      this.initEditor();
    }

    wx.request({
      url: `${config.apiUrl}/content`,
      method:'GET',
      success: res => {
        console.log(res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})